# -*- coding: utf-8 -*-
'''
@文件    :exceptions.py
@说明    :异常处理类
@时间    :2025/08/09 15:55:11
@作者    :浪晋
@版本    :1.0
'''
import traceback
from fastapi import Request, status
from fastapi.exceptions import RequestValidationError, ResponseValidationError
from starlette.exceptions import HTTPException
from fastapi.responses import JSONResponse
from app.core.database import record_request_log


async def http_exception_handler(request: Request, exc: HTTPException):
    """
    @功能    :http异常处理器
    @参数    :
    @返回值  :
    @时间    :2024/10/18 17:04:35
    @作者    :浪晋
    @版本    :1.0
    """
    if exc.status_code == 401:
        content=dict(code=9, message=exc.detail)
    else:
        content=dict(code=0, message=exc.detail)
    response = JSONResponse(content=content, status_code=exc.status_code)
    await record_request_log(request, response)
    return response


async def validate_request_handler(request: Request, exc: RequestValidationError):
    """
    @功能    :请求参数异常处理器
    @参数    :
    @返回值  :
    @时间    :2024/10/18 17:05:10
    @作者    :浪晋
    @版本    :1.0
    """
    errors = []
    for error in exc.errors():
        loc = ".".join(map(str, error["loc"]))  # 转换为可读的路径（如 "body.quantity"）
        msg = error["msg"]
        errors.append({"loc": loc, "msg": msg})
    content=dict(code=0, message="请求参数校验不通过,请检查参数后再试.", data=errors)
    response = JSONResponse(content, status_code=status.HTTP_400_BAD_REQUEST)
    response = await record_request_log(request, response)
    return response


async def validate_response_handler(request: Request, exc: ResponseValidationError) -> JSONResponse:
    """
    @功能    :响应参数异常处理器
    @参数    :
    @返回值  :
    @时间    :2025/08/10 04:26:52
    @作者    :浪晋
    @版本    :1.0
    """
    content=dict(code=0, message="响应校验不通过,请检查参数后再试.", data=exc.body)
    response = JSONResponse(content, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
    response = await record_request_log(request, response)
    return response


async def internal_exception_handler(request: Request, exc: Exception) -> JSONResponse:
    """
    @功能    :内部错误
    @参数    :
    @返回值  :
    @时间    :2025/08/10 04:26:52
    @作者    :浪晋
    @版本    :1.0
    """
    content=dict(code=0, message="服务器错误,请联系管理员.", data=str(exc))
    response = JSONResponse(content, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
    errorlog = traceback.format_exc()
    response = await record_request_log(request, response, errorlog)
    return response